package com.anxin.act.utils;

import com.anxin.act.task.dao.WfActHiCommentDao;
import com.anxin.act.task.dao.WfActHiTaskDao;
import com.anxin.act.task.entity.WfActHiComment;
import com.anxin.act.task.entity.WfActHiTask;
import com.anxin.act.task.service.WfActHiCommentService;
import com.anxin.act.task.service.WfActHiTaskService;
import com.anxin.common.utils.spring.SpringUtils;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.task.Comment;

import java.util.ArrayList;
import java.util.List;

/**
 * 流程审批意见工具类
 */
public class ActCommentUtils {


    private static TaskService taskService = SpringUtils.getBean(TaskService.class);
    private static WfActHiCommentDao wfActHiCommentDao = SpringUtils.getBean(WfActHiCommentDao.class);
    private static WfActHiTaskDao wfActHiTaskDao = SpringUtils.getBean(WfActHiTaskDao.class);
    private static HistoryService historyService = SpringUtils.getBean(HistoryService.class);

    public static List<WfActHiComment> getCommentList(HistoricActivityInstance histIns){
        List<WfActHiComment> res = new ArrayList<>();

        if ("-2".equals(histIns.getAssignee())){
            WfActHiTask wfActHiTask = wfActHiTaskDao.findBySourceIdAndSourceType(histIns.getTaskId(), "comment");
            res = wfActHiCommentDao.findList(new WfActHiComment(wfActHiTask.getId()));
        }else {
            List<Comment> commentList = taskService.getTaskComments(histIns.getTaskId());
            for (Comment comment : commentList) {
                res.add(new WfActHiComment(comment));
            }
        }

        return res;
    }

    public static List<WfActHiComment> getCommentList(HistoricTaskInstance histIns){
        List<WfActHiComment> res = new ArrayList<>();

        if ("-2".equals(histIns.getAssignee())){
            WfActHiTask wfActHiTask = wfActHiTaskDao.findBySourceIdAndSourceType(histIns.getId(), "comment");
            res = wfActHiCommentDao.findList(new WfActHiComment(wfActHiTask.getId()));
        }else {
            List<Comment> commentList = taskService.getTaskComments(histIns.getId());
            for (Comment comment : commentList) {
                res.add(new WfActHiComment(comment));
            }
        }

        return res;
    }




    /**
     * 获取最后一个任务的审批意见
     * @param actId
     * @return
     */
    public static List<WfActHiComment> getLastTaskCommentList(String actId){
        List<HistoricTaskInstance> taskInstanceList = historyService.createHistoricTaskInstanceQuery().processInstanceId(actId).orderByTaskCreateTime().desc().orderByHistoricTaskInstanceEndTime().desc().list();
        return ActCommentUtils.getCommentList(taskInstanceList.get(0));
    }

}
